package com.hhit.zhgd.utils

import jakarta.xml.bind.DatatypeConverter
import org.slf4j.LoggerFactory
import java.awt.image.BufferedImage
import java.io.*
import java.nio.file.Files
import java.nio.file.Paths
import java.util.*
import javax.imageio.ImageIO
import javax.imageio.stream.FileImageOutputStream

object UtilImage {
    private val log= LoggerFactory.getLogger(UtilImage::class.java)

    /**
     * 保存图片到本地
     */
    fun savaImage(FilePath: String?, imageId: String?, data: ByteArray): String? {
        var imagePath: String? = null
        val folder = File(FilePath)
        if (!folder.exists()) {
            folder.mkdirs()
        }
        imagePath = String.format(
            "%s/%s",
            FilePath,
            imageId
        )
        try {
            val imageOutput = FileImageOutputStream(File(imagePath))
            imageOutput.write(data, 0, data.size)
            imageOutput.close()
            log.info("Make Picture success,Please find image in $imagePath")
        } catch (ex: Exception) {
            log.error("Exception: $ex")
        }
        return imagePath
    }

    /**
     * 转换图片路径
     * @param filepath
     * @return
     */
    fun PathRemoveOutFolder(filepath: String?, outFolder: String, configUrl: String): String? {
        if (filepath == null || filepath == "") return ""
        var filename: String = filepath
        if (filename.startsWith(outFolder)) {
            val startIndex = outFolder.length
            filename = filename.substring(startIndex)
        }
        filename = configUrl + filename.substring(1)
        return filename
    }

    @Throws(IOException::class)
    fun ResizeImage(imgFile: String, dstWidth: Int, dstHeight: Int, minHeight: Int) {
        var dstWidth = dstWidth
        var dstHeight = dstHeight
        val f = File(imgFile)
        if (f.canRead()) {
            val bi = ImageIO.read(f)
            if (bi.width > dstWidth) {
                if (dstHeight <= 0) {
                    dstHeight = bi.height * dstWidth / bi.width
                    if (minHeight > 0 && dstHeight < minHeight) {
                        dstWidth = dstWidth * minHeight / dstHeight
                        dstHeight = minHeight
                    }
                }
                val newImage = BufferedImage(dstWidth, dstHeight, bi.type)
                val g = newImage.graphics
                g.drawImage(bi, 0, 0, dstWidth, dstHeight, null)
                g.dispose()

                //String tmp = imgFile.substring(0, imgFile.lastIndexOf("."));
                if (imgFile.lowercase(Locale.getDefault()).endsWith(".jpg")) ImageIO.write(
                    newImage,
                    "jpg",
                    f
                ) else if (imgFile.lowercase(Locale.getDefault()).endsWith(".png")) ImageIO.write(
                    newImage,
                    "png",
                    f
                ) else ImageIO.write(newImage, imgFile.substring(imgFile.lastIndexOf(".") + 1), f)
            }
        }
    }

    fun ImageToBase64(imagePath: String?): String? {
        try {
            val data = Files.readAllBytes(Paths.get(imagePath))
            return DatatypeConverter.printBase64Binary(data)
        } catch (e: Exception) {
            log.info(String.format("ImageToBase64(%s)", imagePath), e)
        }
        return ""
    }

    fun Base64ToImage(imageData: String?, imagePath: String?, imageId: String?) {
        val decodedBytes = Base64.getDecoder().decode(imageData)
        // 创建目录，如果目录已存在则不会创建，如果创建失败则抛出异常
        val directoryPath = Paths.get(imagePath)
        try {
            Files.createDirectories(directoryPath)
        } catch (e: IOException) {
            log.error("无法创建目录：{}", imagePath, e)
            return  // 或者抛出异常，取决于你的业务逻辑
        }
        val outputFile = File(String.format("%s" + File.separator + "%s", imagePath, imageId))
        try {
            FileOutputStream(outputFile).use { out ->
                out.write(decodedBytes)
                log.info("图片已生成并保存到：{}", outputFile.absolutePath)
            }
        } catch (e: IOException) {
            log.error("写入图片文件时出错：{}", outputFile.absolutePath, e)
            // 这里可以添加额外的错误处理逻辑，比如重试或者记录更详细的错误信息
        }
    }

    fun Base64ToByte(imagePath: String?): ByteArray? {
        var data: ByteArray? = null
        try {
            data = DatatypeConverter.parseBase64Binary(imagePath)
        } catch (e: Exception) {
            log.error("Base64ToByte:错误！")
        }
        return data
    }

    @Throws(Exception::class)
    fun readInputStream(inStream: InputStream): ByteArray? {
        val outStream = ByteArrayOutputStream()
        val buffer = ByteArray(1024)
        var len = 0
        while (inStream.read(buffer).also { len = it } != -1) {
            outStream.write(buffer, 0, len)
        }
        inStream.close()
        return outStream.toByteArray()
    }

    @Throws(IOException::class)
    fun convertImageToByteArray(imagePath: String?): ByteArray? {
        val imageFile = File(imagePath)
        val fis = FileInputStream(imageFile)
        val bos = ByteArrayOutputStream()
        val buffer = ByteArray(1024)
        var bytesRead: Int
        while (fis.read(buffer).also { bytesRead = it } != -1) {
            bos.write(buffer, 0, bytesRead)
        }
        fis.close()
        bos.close()
        return bos.toByteArray()
    }
}